<script>
	import store from './store';
	import http from './common/request';
	import * as enums from './common/enums';
	import * as wsApi from './common/wssocket';
	import UNI_APP from '@/.env.js'
	
	export default {
		data() {
			return {
				audioTip: null
			}
		},
		methods: {
			checkUpdateApp() {
				plus.runtime.getProperty(plus.runtime.appid,function(widgetinfo) {
					console.log('更新===',widgetinfo);
					
					uni.request({
						// url: 'https://ktalkapi.qiaonongrenzf.cn/user/getNewAppVersion', // 测试
						url: 'https://ktalkapimap.chainaibit.com/user/getNewAppVersion', // 正式
						success: (srcData) => {
							console.log('srcData123===',srcData)
							let data = srcData.data.data;
							let version = widgetinfo.versionCode, //用户当前版本
								appVersion = data.versionCode, //升级包版本
								appurl = data.androidUrl, //升级包地址
								intro = data.versionInfo; //升级包提示
								
							//如果用户版本号小于升级包版本号，先升级
							if(data && (version<appVersion)) {
								uni.showModal({
									title: "更新提示",
									confirmText: "立即升级",
									content: intro,
									showCancel: false,
									success: (res) => {
										if (res.confirm) {
											uni.showLoading({
												title: "正在更新",
												mask: true
											})
											uni.downloadFile({
												url: appurl,
												success: (download) => {
													if (download.statusCode == 200) {
														plus.runtime.install(download.tempFilePath, {force: false},() => {
															uni.hideLoading();
															plus.runtime.restart(); //更新成功启动
														},(err) => { //若没下载成功还是去下载
															uni.hideLoading();
															uni.showToast({
																title: "更新失败，将跳转下载页面",
																icon: "none",
																duration: 2000
															})
														})
														setTimeout( function() { plus.runtime.openURL( appurl ); }, 2000)
													}
												}
											})
										}else if (res.cancel) {
											console.log('用户点击取消');
											uni.showToast({
												title: "版本更新,请先升级",
												icon: "none",
												duration: 2000
											})
											//退出app
											setTimeout(function() {
												plus.runtime.quit();
											}, 2000)
										}
									}
								})
							}
						},
						fail: () => {
							console.log('请求报错')
						}
					})
				}) 
			},
			
			
			init() {
				// 加载数据
				store.dispatch("load").then(() => {
					// 初始化websocket
					// this.initWebSocket();
				}).catch((e) => {
					console.log(e);
					this.exit();
				})
			},
			initWebSocket() {
				// console.log(store.state.userStore.userInfo)
				let loginInfo = uni.getStorageSync("loginInfo")
				wsApi.init();
				wsApi.connect(UNI_APP.WS_URL,  uni.getStorageSync('token'));
				wsApi.onConnect(() => {
					// 加载离线消息
					this.pullPrivateOfflineMessage(store.state.chatStore.privateMsgMaxId);
					this.pullGroupOfflineMessage(store.state.chatStore.groupMsgMaxId);
				});
				wsApi.onMessage((cmd, msgInfo) => {
					if (cmd == 2) {
						// 异地登录，强制下线
						uni.showModal({
							content: '您已在其他地方登陆，将被强制下线',
							showCancel: false,
						})
						this.exit();
					} else if (cmd == 3) {
						// 私聊消息
						// console.log('msgInfo===',msgInfo)
						
						this.handlePrivateMessage(msgInfo);
					} else if (cmd == 4) {
						// 群聊消息
						this.handleGroupMessage(msgInfo);
					}
				});
				wsApi.onClose((res) => {
					// 1000是客户端正常主动关闭
					if (res.code != 1000) {
						// 重新连接
						uni.showToast({
							title: '连接已断开，尝试重新连接...',
							icon: 'none',
						})
						let loginInfo = uni.getStorageSync("loginInfo")
						wsApi.reconnect(UNI_APP.WS_URL, loginInfo.accessToken);
					}
				})
			},
			pullPrivateOfflineMessage(minId) {
				http({
					url: "/message/private/pullOfflineMessage?minId=" + minId,
					method: 'get'
				});
			},
			pullGroupOfflineMessage(minId) {
				http({
					url: "/message/group/pullOfflineMessage?minId=" + minId,
					method: 'get'
				});
			},
			handlePrivateMessage(msg) {
				// console.log('msg===',msg)
				if(msg.type == 14) {
					uni.$emit('applyFriend',msg)
					return
				}
				
				
				// 消息加载标志
				if (msg.type == enums.MESSAGE_TYPE.LOADDING) {
					store.commit("loadingPrivateMsg", JSON.parse(msg.content))
					return;
				}
				// 消息已读处理，清空已读数量
				if (msg.type == enums.MESSAGE_TYPE.READED) {
					store.commit("resetUnreadCount", {
						type: 'PRIVATE',
						targetId: msg.recvId
					})
					return;
				}
				// 消息回执处理,改消息状态为已读
				if (msg.type == enums.MESSAGE_TYPE.RECEIPT) {
					store.commit("readedMessage", { friendId: msg.sendId })
					return;
				}
				
				// debugger
				// 标记这条消息是不是自己发的
				msg.selfSend = msg.sendId == store.state.userStore.userInfo.id;
				// console.log('store.state.userStore.userInfo.id===',store.state.userStore.userInfo.id)
				
				// 好友id
				let friendId = msg.selfSend ? msg.recvId : msg.sendId;
				console.log('friendId===',friendId)
				
				this.loadFriendInfo(friendId).then((friend) => {
					this.insertPrivateMessage(friend, msg);
				})

			},
			insertPrivateMessage(friend, msg) {
				// console.log('msg===',msg)
				// console.log('friend===',friend)
				
				// webrtc 信令
				if (msg.type >= enums.MESSAGE_TYPE.RTC_CALL &&
					msg.type <= enums.MESSAGE_TYPE.RTC_CANDIDATE) {}

				let chatInfo = {
					type: 'PRIVATE',
					targetId: friend.id,
					showName: friend.nickName,
					headImage: friend.headImage
				};
				// 打开会话
				store.commit("openChat", chatInfo);
				// 插入消息
				store.commit("insertMessage", msg);
				// 播放提示音
				!msg.selfSend && this.playAudioTip();

			},
			handleGroupMessage(msg) {
				// 消息加载标志
				if (msg.type == enums.MESSAGE_TYPE.LOADDING) {
					store.commit("loadingGroupMsg",JSON.parse(msg.content))
					return;
				}
				// 消息已读处理
				if (msg.type == enums.MESSAGE_TYPE.READED) {
					// 我已读对方的消息，清空已读数量
					let chatInfo = {
						type: 'GROUP',
						targetId: msg.groupId
					}
					store.commit("resetUnreadCount", chatInfo)
					return;
				}
				// 消息回执处理
				if (msg.type == enums.MESSAGE_TYPE.RECEIPT) {
					// 更新消息已读人数
					let msgInfo = {
						id: msg.id,
						groupId: msg.groupId,
						readedCount: msg.readedCount,
						receiptOk: msg.receiptOk
					};
					store.commit("updateMessage", msgInfo)
					return;
				}
				// 标记这条消息是不是自己发的
				msg.selfSend = msg.sendId == store.state.userStore.userInfo.id;
				this.loadGroupInfo(msg.groupId).then((group) => {
					// 插入群聊消息
					this.insertGroupMessage(group, msg);
				})

			},
			insertGroupMessage(group, msg) {
				let chatInfo = {
					type: 'GROUP',
					targetId: group.id,
					showName: group.remark,
					headImage: group.headImage
				};
				// 打开会话
				store.commit("openChat", chatInfo);
				// 插入消息
				store.commit("insertMessage", msg);
				// 播放提示音
				!msg.selfSend && this.playAudioTip();
			},
			loadFriendInfo(id) {
				
				return new Promise((resolve, reject) => {
					let friend = store.state.friendStore.friends.find((f) => f.id == id);
					// console.log('store.state.friendStore.friends===',store.state.friendStore.friends)
					
					if (friend) {
						resolve(friend);
					} else {
						http({
							url: `/friend/find/${id}`,
							method: 'get'
						}).then((friend) => {
							store.commit("addFriend", friend);
							resolve(friend)
						})
					}
				});
			},
			loadGroupInfo(id) {
				return new Promise((resolve, reject) => {
					let group = store.state.groupStore.groups.find((g) => g.id == id);
					if (group) {
						resolve(group);
					} else {
						http({
							url: `/group/find/${id}`,
							method: 'get'
						}).then((group) => {
							resolve(group)
							store.commit("addGroup", group);
						})
					}
				});
			},
			exit() {
				console.log("exit");
				wsApi.close(1000);
				uni.removeStorageSync("loginInfo");
				uni.reLaunch({
					url: "/pages/login/login"
				})
				store.dispatch("unload");
			},
			playAudioTip() {
				// 音频播放无法成功
				// this.audioTip = uni.createInnerAudioContext();
				// this.audioTip.src =  "/static/audio/tip.wav";
				// this.audioTip.play();
			},
		},
		onShow() {
			// #ifdef APP-PLUS 
			uni.getSystemInfo({
				success: (res) => {
					if (res.platform == "android") {
						this.checkUpdateApp();
						// console.log('测试包')
					}
				}
			})
			// #endif
		},
		
		onLaunch() {
			const isFirstLaunch = uni.getStorageSync('isFirstLaunch') || true;
			if (isFirstLaunch) {
			  // 这里是首次启动时的逻辑处理
			  // console.log('首次启动应用');
			  // uni.setStorageSync('isFirstLaunch', true);
			} else {
			  // console.log('非首次启动应用');
			}
			
			// 登录状态校验
			// console.log('token===',uni.getStorageSync("token"))
			const whiteList = [
				// "/pages/browse/index"
				// "/",
				"/pages/chat/chat",
				"/pages/friend/friend"
			]
			
			const list = ["navigateTo", "redirectTo", "reLaunch", "switchTab"];
			list.forEach(item => {
				uni.addInterceptor(item,{
					invoke(e) {
						let url = e.url.split('?')[0]
						// console.log('url===',url)
						
						let notNeed = whiteList.includes(url)
						
						if(notNeed) {
							uni.showToast({
								title: '敬请期待',
								icon: 'none'
							})
							return false
						}
						
					}
				})
			})
			
			if (uni.getStorageSync("token")) {
				// 初始化
				// this.init()
			}
		},
		
	}
</script>

<style lang="scss">
	@import url('./static/icon/iconfont.css');
	
	// $theme-color-a: #3F93FF;
	page {
		background: #f8f8f8;
	}
	

	.tab-page {
		// #ifdef H5
		height: calc(100vh - 46px - 50px); // h5平台100vh是包含了顶部和底部，需要减去
		// #endif
		// #ifndef H5
		height: calc(100vh);
		// #endif
		background-color: #f8f8f8;
	}

	.page {
		// #ifdef H5
		height: calc(100vh - 45px); // h5平台100vh是包含了顶部，需要减去
		// #endif
		// #ifndef H5
		height: calc(100vh);
		// #endif
		background-color: #f8f8f8;
	}
</style>